import './index.css'
import {Button, Form, Input, message, Modal, Popconfirm, Select, Switch, Table} from "antd"
import {useCallback, useEffect, useState} from "react"
import {getIcon, selectIconOptions} from "../../../utils/dynamic-icon"
import {useOutletContext} from "react-router-dom"
import {
    changeMenuItem,
    changeMenuShow,
    createMenuItem,
    deleteMenuItem,
    getAllMenu,
    moveDown,
    moveUp
} from "../../../request/menu"
import {DatabaseOutlined} from "@ant-design/icons"

const columns = [
    {
        title: '菜单名称',
        dataIndex: 'label',
        key: 'label',
        align: 'left',
        width: 300
    },
    {
        title: '前端名称',
        dataIndex: 'name',
        key: 'name',
        align: 'left',
        width: 300
    },
    {
        title: '前端图标',
        dataIndex: 'icon',
        key: 'icon',
        align: 'center',
        width: 100
    },
    {
        title: '是否显示',
        dataIndex: 'show',
        key: 'show',
        align: 'center',
        width: 100
    },
    {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        align: 'center'
    }
]

function Menu() {
    const [onMenuChange] = useOutletContext()
    let [data, setData] = useState([])
    let [editing, setEditing] = useState({})
    let [title, setTitle] = useState('')
    const [form] = Form.useForm()

    const loadMenu = useCallback(() => {
        function changeShow(item, show) {
            changeMenuShow(item.namePath, show).then(() => {
                onMenuChange()
            }).catch(({msg}) => message.error(msg))
        }

        function deleteItem(item) {
            deleteMenuItem(item.namePath).then(() => {
                onMenuChange()
                loadMenu()
                message.success('删除成功')
            }).catch(({msg}) => message.error(msg))
        }

        function moveItemUp(item) {
            moveUp(item.namePath).then(() => {
                onMenuChange()
                loadMenu()
                message.success('成功上移')
            }).catch(({msg}) => message.error(msg))
        }

        function moveItemDown(item) {
            moveDown(item.namePath).then(() => {
                onMenuChange()
                loadMenu()
                message.success('成功下移')
            }).catch(({msg}) => message.error(msg))
        }

        let key = 0

        function loadMenuInner(data, parentNamePath) {
            if (!data) return undefined
            return data.map(item => {
                const namePath = [...parentNamePath, item.name]
                const newItem = {
                    key: ++key,
                    label: item.label,
                    name: item.name,
                    icon: getIcon(item.icon),
                    iconName: item.icon,
                    namePath,
                    children: loadMenuInner(item.children, namePath)
                }
                newItem.show = <Switch defaultChecked={item.show} onChange={
                    (checked) => changeShow(newItem, checked)
                }/>
                newItem.operation = (
                    <>
                        <Button type="link" onClick={() => {
                            setTitle('编辑菜单')
                            setEditing(newItem)
                            form.setFieldsValue(newItem)
                        }}>编辑</Button>
                        <Button type="link" onClick={() => {
                            setTitle('添加子菜单')
                            const appendItem = {
                                key: -1,
                                label: undefined,
                                name: undefined,
                                iconName: undefined,
                                namePath
                            }
                            setEditing(appendItem)
                            form.setFieldsValue(appendItem)
                        }}>添加子菜单</Button>
                        <Button type="link" onClick={() => moveItemUp(newItem)}>上移</Button>
                        <Button type="link" onClick={() => moveItemDown(newItem)}>下移</Button>
                        <Popconfirm
                            title="确认删除"
                            description="你确定要删除该项菜单吗?"
                            onConfirm={() => {
                                deleteItem(newItem)
                            }}
                            okText="是"
                            cancelText="否"
                        >
                            <Button type="link">删除</Button>
                        </Popconfirm>
                    </>
                )
                return newItem
            })
        }

        getAllMenu().then(menu => {
            setData(loadMenuInner(menu, []))
        }).catch(({msg}) => message.error(msg))
    }, [form, onMenuChange])
    useEffect(loadMenu, [loadMenu])

    function tryEdit({label, name, iconName}) {
        const fun = editing.key !== -1 ? changeMenuItem : createMenuItem
        fun(editing.namePath, label, name, iconName).then(() => {
            setEditing({})
            onMenuChange()
            loadMenu()
            message.success(editing.key !== -1 ? '修改成功' : '创建成功')
        }).catch(({msg}) => message.error(msg))
    }

    return (
        <>
            <div className="content-item-box">
                <DatabaseOutlined/>
                <span>数据列表</span>
                <div className="blank"></div>
                <Button onClick={() => {
                    setTitle('添加菜单')
                    const appendItem = {
                        key: -1,
                        label: undefined,
                        name: undefined,
                        iconName: undefined,
                        namePath: []
                    }
                    setEditing(appendItem)
                    form.setFieldsValue(appendItem)
                }}>添加</Button>
            </div>
            <Modal
                title={title}
                open={editing.key}
                //onOk={handleOk}
                onCancel={() => setEditing({})}
                footer={[]}
                width={300}
            >
                <Form
                    className="edit-form"
                    onFinish={tryEdit}
                    form={form}>
                    <Form.Item name="label" label="菜单名称" rules={[
                        {
                            required: true,
                            message: '请输入菜单名称'
                        }
                    ]}>
                        <Input placeholder="请输入菜单名称"/>
                    </Form.Item>
                    <Form.Item name="name" label="前端名称" rules={[
                        {
                            required: true,
                            message: '请输入前端名称'
                        }
                    ]}>
                        <Input placeholder="请输入前端名称"/>
                    </Form.Item>
                    <Form.Item name="iconName" label="前端图标" rules={[
                        {
                            required: true,
                            message: '请选择前端图标'
                        }
                    ]}>
                        <Select options={selectIconOptions} placeholder="请选择前端图标"/>
                    </Form.Item>
                    <Form.Item>
                        <Button onClick={() => setEditing({})}>取消</Button>
                        <Button type="primary" htmlType="submit">确定</Button>
                    </Form.Item>
                </Form>
            </Modal>
            <Table
                columns={columns}
                dataSource={data}
                pagination={false}
            />
        </>
    )
}

export default Menu